package com.discuz.spider.jpkoo;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.util.Map;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import com.discuz.spider.WebClientAgent;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlImage;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.util.Cookie;
import com.gargoylesoftware.htmlunit.xml.XmlPage;

public class JPKooLogin {

	private static String URL = "http://www.jpkoo.com/member.php?mod=logging&action=login&referer=http%3A%2F%2Fwww.jpkoo.com%2F";
	private static String FORM_XPATH = "login";
	private static String U_INPUT_XPATH = "username";
	private static String P_INPUT_XPATH = "password";
	private static String U = "ibmdba";
	private static String P = "123456789";
	private static String LOGIN_BUTTON_XPATH = "loginsubmit";

	static WebClient client = WebClientAgent.get();

	public static void main(String[] args) throws MalformedURLException,
			IOException, Throwable {
		login();
	}

	public static HtmlPage login() throws Throwable, MalformedURLException,
			IOException {

		int ret = 1;

		HtmlPage page = client.getPage(URL);

		HtmlForm form = page.getFormByName(FORM_XPATH);
		HtmlInput u = form.getInputByName(U_INPUT_XPATH);
		HtmlInput p = form.getInputByName(P_INPUT_XPATH);
		HtmlInput code = form.getInputByName("seccodeverify");
		HtmlButton btn = form.getButtonByName(LOGIN_BUTTON_XPATH);

		// se hash
		HtmlInput sechash = form.getInputByName("sechash");
		String sHash = sechash.getAttribute("value");

		u.blur();
		u.setValueAttribute(U);

		p.blur();
		p.setValueAttribute(P);

		code.blur();
		code.setValueAttribute(getCode(sHash));

		HtmlPage homePage = btn.click();

		String ctx = homePage.asText();
		if (ctx.contains("登录失败")) {
			System.out.println("login failed");
			ret = 2;
		} else if (ctx.contains("设置")) {

			System.out.println("login succeedful");
			ret = 3;
			// save cookie
		} else {
			ret = 4;
			System.out.println("login no");
		}

		return homePage;
	}

	public static String getCode(String hash) {
		String valicodeStr = null;
		try {
			XmlPage p = (XmlPage) client
					.getPage("http://www.jpkoo.com/misc.php?mod=seccode&action=update&idhash="
							+ hash + "&inajax=1&ajaxtarget=seccode_" + hash);

			Set<Cookie> set = p.getWebClient().getCookieManager().getCookies();
			for (Cookie c : set) {
				System.out.println(c.getName() + "=" + c.getValue());
			}

			String c = p.asText();
			int pos = c.indexOf("src=");
			c = c.substring(
					pos + 5,
					pos
							+ "src='misc.php?mod=seccode&update=42462&idhash=Sz9nEQ00'"
									.length() - 1);

			String codeURL = "http://www.jpkoo.com/" + c;

			WebRequest request = new WebRequest(new java.net.URL(codeURL),
					"image/png,image/*;q=0.8,*/*;q=0.5");

			request.setAdditionalHeader("Accept-Language",
					"zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
			request.setAdditionalHeader("Connection", "keep-alive");
			request.setAdditionalHeader("Host", "www.jpkoo.com");
			request.setAdditionalHeader("Referer",
					"http://www.jpkoo.com/member.php?mod=register");
			request.setAdditionalHeader("User-Agent",
					"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0");

			Map<String, String> r = request.getAdditionalHeaders();

			InputStream in = client.getPage(request).getWebResponse()
					.getContentAsStream();

			BufferedImage bufferedImage = ImageIO.read(in);

			JFrame f2 = new JFrame();
			JLabel l = new JLabel();
			l.setSize(200, 100);

			l.setIcon(new ImageIcon(bufferedImage));
			f2.getContentPane().add(l);
			f2.setSize(180,100);
			f2.setTitle("验证码");
			f2.setVisible(true);

			valicodeStr = JOptionPane.showInputDialog("请输入验证码：");
			f2.dispose();

			in.close();

		} catch (FailingHttpStatusCodeException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return valicodeStr;
	}

}
